package android.textIt.frontend.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.textIt.R;
import android.textIt.backend.dao.GroupDao;
import android.textIt.backend.dao.MessageDao;
import android.textIt.backend.model.Group;
import android.textIt.backend.model.Message;
import android.textIt.backend.model.Status;
import android.textIt.frontend.adapter.MessageAdapter;
import android.textIt.util.TextItUtil;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class ViewMessageActivity extends Activity {
  private static int ACTIVITY_SPEAK_MSG = 0;
  private static ArrayList<String> voiceData;
  private static MessageDao messageDAO;
  private static GroupDao groupDAO;
  private int to;

  // int groupId;
  Group group;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_view_messages);
    attachButtonOnClickListners();
    Bundle extras = getIntent().getExtras();
    int id = Integer.parseInt(extras.getString("id"));
    to = extras.getInt("to");
    messageDAO = new MessageDao(this);
    groupDAO = new GroupDao(this);
    TextView members = (TextView) findViewById(R.id.txtMessageMembers);
    group = groupDAO.getGroupById(id);
    members.setText(TextItUtil.membersToString(groupDAO.getUsersInGroup(group)));
    bindView();
  }

  private void bindView() {
    ListView listView = (ListView) findViewById(R.id.listMessages);
    List<Message> msgs = messageDAO.getAllMessagesWithGroup(group);
    MessageAdapter madapter = new MessageAdapter(this, msgs);
    listView.setAdapter(madapter);
    listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    listView.setStackFromBottom(true);
    listView.invalidate();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.view_messages_menu, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    // TextView idTextView = (TextView)info.targetView.findViewById(R.id.TxtGroupId);
    // int item_id = Integer.parseInt((String) idTextView.getText());
    switch (item.getItemId()) {
    case R.id.add_member:
      addMember();
      return true;
    case R.id.save_group:
      saveGroup();
      return true;
    case R.id.delete_convo:
      deleteConversation();
      return true;
    default:
      return super.onContextItemSelected(item);
    }
  }

  private void saveGroup() {
    final Dialog dialog = new Dialog(ViewMessageActivity.this);
    dialog.setContentView(R.layout.dlg_save_group);
    dialog.setTitle("Save group");

    final TextView txtName = (TextView) dialog.findViewById(R.id.TxtSaveGroupName);

    Button btnSave = (Button) dialog.findViewById(R.id.btnSaveGroup);
    btnSave.setOnClickListener(new Button.OnClickListener() {
      @Override
      public void onClick(View arg0) {
        String name = txtName.getText().toString().trim();

        if (name.length() == 0) {
          new AlertDialog.Builder(ViewMessageActivity.this).setTitle("Error")
                                                           .setMessage("Please enter a group name")
                                                           .setNeutralButton("Ok",
                                                                             new DialogInterface.OnClickListener() {
                                                                               public void onClick(DialogInterface dlg,
                                                                                                   int sumthin) {

                                                                               }
                                                                             })
                                                           .show();
          return;
        }
        group.setName(name);
        group.setIsTemporary(false); // make it a defined group
        groupDAO.updateGroup(group);
        dialog.dismiss();
      }
    });

    Button btnCancel = (Button) dialog.findViewById(R.id.btnCancelGroup);
    btnCancel.setOnClickListener(new Button.OnClickListener() {
      public void onClick(View arg0) {
        dialog.cancel();
      }
    });
    dialog.show();
    return;

  }

  private void deleteConversation() {
    // TODO Auto-generated method stub

  }

  private void addMember() {
    // TODO Auto-generated method stub

  }

  private void attachButtonOnClickListners() {
    Button btnSend = (Button) findViewById(R.id.btnSend);
    btnSend.setOnClickListener(new Button.OnClickListener() {
      @Override
      public void onClick(View arg0) {
        TextView tvMsg = (TextView) findViewById(R.id.txtMessageToSend);
        Message m = new Message();
        Status s = new Status(1, "unread");
        m.setContent(tvMsg.getText().toString());
        m.setSender(MainActivity.phoneOwner);
        m.setReceiver(group);
        m.setStatus(s);
        m.setReference_id(-1);
        messageDAO.createMessage(m);
        if (to == TextItUtil.TO_INDIVIDUAL)
          messageDAO.sendMessage(m);
        else
          messageDAO.sendGroupMessage(m);
        tvMsg.setText("");
        bindView();
      }
    });

    Button btnGoBack = (Button) findViewById(R.id.btnGoBack);
    btnGoBack.setOnClickListener(new Button.OnClickListener() {
      @Override
      public void onClick(View arg0) {
        Intent result = new Intent();
        setResult(RESULT_OK, result);
        finish();
        return;
      }
    });

    ImageButton btnMic = (ImageButton) findViewById(R.id.btnMic);
    btnMic.setOnClickListener(new ImageButton.OnClickListener() {
      @Override
      public void onClick(View arg0) {
        try {
          Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
          intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                          RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
          intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak now");
          startActivityForResult(intent, ACTIVITY_SPEAK_MSG);
        }
        catch (Exception ex) {

        }
      }
    });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
      voiceData = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
      if (requestCode == ACTIVITY_SPEAK_MSG) {
        TextView item = (TextView) findViewById(R.id.txtMessageToSend);
        if (!voiceData.isEmpty())
          item.setText(voiceData.get(0));
      }
    }
    catch (Exception exq) {

    }
  }
}
